<template>
  <div class="detail">
    <el-form ref="postForm" :rules="rules" :model="postForm" class="form-container">
      <sticky :z-index="10" :class-name="'sticky'">
        <el-button v-if="!isEdit" @click.prevent.stop="showHelp">显示帮助</el-button>
        <el-button v-loading="loading" style="margin-left: 10px;" type="success" @click="submitForm">
          {{ isEdit ? '编辑电子书' : '新增电子书' }}
        </el-button>
      </sticky>
      <div class="detail-container">
        <warning />
        <el-row>
          <el-col :span="24">
            <!-- 编写具体表单控件 -->
            <uploadBook
              :is-edit="isEdit"
              :file-list="fileList"
              @onSuccess="onSuccess"
              @onRemove="onRemove"
            />
          </el-col>
          <el-col :span="24">
            <el-form-item style="margin-bottom: 40px;" prop="title">
              <mdinput :value="postForm.title" :maxlength="100" name="name" required>
                书名
              </mdinput>
            </el-form-item>
            <div>
              <el-row>
                <el-col :span="12" class="form-item-author">
                  <el-form-item prop="author" :label-width="labelWidth" label="作者：">
                    <el-input
                      v-model="postForm.author"
                      placeholder="作者"
                      style="width: 100%"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item prop="publisher" :label-width="labelWidth" label="出版社：">
                    <el-input
                      v-model="postForm.publisher"
                      placeholder="出版社"
                      style="width: 100%"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item prop="language" :label-width="labelWidth" label="语言：">
                    <el-input
                      v-model="postForm.language"
                      placeholder="语言"
                      style="width: 100%"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item :label-width="labelWidth" label="根文件：">
                    <el-input
                      v-model="postForm.rootFile"
                      placeholder="根文件"
                      style="width: 100%"
                      disabled
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item :label-width="labelWidth" label="文件路径：">
                    <el-input
                      v-model="postForm.filePath"
                      placeholder="文件路径"
                      style="width: 100%"
                      disabled
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item :label-width="labelWidth" label="解压路径：">
                    <el-input
                      v-model="postForm.unzipPath"
                      placeholder="解压路径"
                      style="width: 100%"
                      disabled
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item :label-width="labelWidth" label="封面路径：">
                    <el-input
                      v-model="postForm.coverPath"
                      placeholder="封面路径"
                      style="width: 100%"
                      disabled
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item :label-width="labelWidth" label="文件名称：">
                    <el-input
                      v-model="postForm.fileName"
                      placeholder="文件名称"
                      style="width: 100%"
                      disabled
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24">
                  <el-form-item label-width="60px" label="封面：">
                    <a v-if="postForm.cover" :href="postForm.cover" target="_blank">
                      <img :src="postForm.cover" class="preview-img">
                    </a>
                    <span v-else>无</span>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24">
                  <el-form-item label-width="60px" label="目录：">
                    <div
                      v-if="contentsTree && contentsTree.length > 0"
                      class="contents-wrapper"
                    >
                      <el-tree :data="contentsTree" @node-click="onContentClick" />
                    </div>
                    <span v-else>无</span>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </el-col>
        </el-row>
      </div>
    </el-form>
  </div>
</template>

<script>
import sticky from './../../../components/Sticky'
import warning from './warning'
import uploadBook from './../../../components/UploadBook'
import mdinput from './../../../components/MDinput'
import { createBook, updateBook, cancelupload, getbook } from './../../../api/book'

const changeChiese = (value) => {
  const obj = {
    author: '作者',
    language: '语言',
    title: '标题',
    publisher: '出版社'
  }
  return obj[value]
}

const rePostForm = {
  author: '',
  title: '',
  publisher: '',
  language: '',
  rootFile: '',
  filePath: '',
  unzipPath: '',
  coverPath: '',
  fileName: '',
  cover: '',
  contents: []
}

export default {
  name: 'Detail',
  components: {
    sticky,
    warning,
    uploadBook,
    mdinput
  },
  props: {
    isEdit: {
      type: Boolean
    }
  },
  data() {
    const validateRequire = (rule, value, callback) => {
      if (!value) {
        this.$message({
          message: rule.field + '为必须有值',
          type: 'error'
        })
        callback(new Error(`${changeChiese(rule.field)}必须有值`))
      } else {
        callback()
      }
    }
    return {
      postForm: {
        author: '',
        title: '',
        publisher: '',
        language: '',
        rootFile: '',
        filePath: '',
        unzipPath: '',
        coverPath: '',
        fileName: '',
        cover: '',
        contents: []
      },
      rules: {
        author: [{ validator: validateRequire }],
        title: [{ validator: validateRequire }],
        publisher: [{ validator: validateRequire }],
        language: [{ validator: validateRequire }]
      },
      loading: false,
      labelWidth: '100px',
      contentsTree: [],
      fileList: []
    }
  },
  created() {
    this.$nextTick(() => {
      const { fileName } = this.$route.params
      if (this.isEdit) {
        this.getBook(fileName)
      }
    })
  },
  methods: {
    getBook(fileName) {
      getbook(fileName).then(res => {
        this.postForm = Object.assign({}, this.postForm, res.data)
        this.contentsTree = res.data.contentsTree
        this.fileList = [{ name: res.data.originalName, url: res.data.text }]
      })
    },
    onSuccess(data) {
      this.postForm = Object.assign({}, this.postForm, data)
      this.contentsTree = data.contentsTree
    },

    onRemove(data) {
      const { filePath, coverPath, unzipPath } = data.data
      this.postForm = rePostForm
      this.contentsTree = []
      this.fileList = []
      this.$refs.postForm.resetFields()
      cancelupload({ filePath, coverPath, unzipPath }).then(res => {
        this.$message({
          type: 'success',
          message: res.msg
        })
      })
    },

    submitForm() {
      this.$refs.postForm.validate((valid, callback) => {
        if (!this.loading) {
          if (valid) {
            const book = Object.assign({}, this.postForm)
            this.loading = true
            if (!this.isEdit) {
              createBook(book).then(response => {
                this.$notify({
                  title: '成功',
                  message: response.msg,
                  type: 'success',
                  duration: 2000
                })
              }).catch(() => {
              })
              this.loading = false
              this.postForm = rePostForm
              this.contentsTree = []
              this.fileList = []
              this.$refs.postForm.resetFields()
            } else {
              const { title, author, publisher, language, fileName, updateType } = book
              updateBook({ title, author, publisher, language, fileName, updateType }).then(response => {
                this.loading = false
                this.$notify({
                  title: '成功',
                  message: response.msg,
                  type: 'success',
                  duration: 2000
                })
              }).catch(() => {
                this.loading = false
              })
            }
          } else {
            return false
          }
        }
      })
    },
    showHelp() {
      console.log('xiaoxian')
    },
    onContentClick(data, node, self) {
      window.open(data.text)
    }
  }
}
</script>

<style lang="scss" scoped>
.detail{
  .form-container{
    .detail-container{
      padding: 40px 50px 20px;
    }
  }
}
</style>
